/**
 * 自定义if命令
 * Created by oscar-yang on 2016/1/26.
 *
 * @example:每次点击按钮时，model.show的值就会在true和false之间切换。
 * <body ng-init="model={show:true, count:0}">
 *     <button ng-click="model.show = !model.show"> Toggle Div </button>
 *     <div if="model.show" ng-init="model.count=model.count+1">
 *         Shown {{model.count}} times
 *     </div>
 * </body>
 */
angular.module('directives.if', [])
.directive('if', function () {
    return {
        transclude : 'element'
        , priority : 500
        , compile : function (element, attr, transclude) {
            return function postLink (scope, element, attr) {
                var childElement, childScope;

                scope.$watch(attr['if'], function (newValue) {
                    if (childElement) {
                        childElement.remove();
                        childScope.$destroy();
                        childElement = undefined;
                        childScope = undefined;
                    }
                    if (newValue) {
                        childScope = scope.$new();
                        childElement = transclude(childScope, function (clone) {
                            element.after(clone);
                        });
                    }
                });
            };
        }
    };
});
